const { createLogger, format, transports } = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const path = require('path');
const { combine, timestamp, printf, errors } = format;

// 日志目录配置
const logDir = path.join(__dirname, '../logs');
const errorLogDir = path.join(logDir, 'errors');
const successLogDir = path.join(logDir, 'success');

// 自定义日志格式
const errorFormat = printf(({ timestamp, level, message, stack }) => {
  return `${timestamp} [${level}] ${stack || message}`;
});

const successFormat = printf(({ timestamp, level, message }) => {
  return `${timestamp} [${level}] ${message}`;
});

// 确保日志目录存在
require('fs').mkdirSync(errorLogDir, { recursive: true });
require('fs').mkdirSync(successLogDir, { recursive: true });

// 创建日志实例
const logger = createLogger({
  level: 'info',
  format: combine(
    timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), // 精确到秒
    errors({ stack: true }), // 包含错误堆栈
    format.json() // JSON格式存储
  ),
  transports: [
    // 错误日志（按天切割）
    new DailyRotateFile({
      filename: path.join(errorLogDir, 'errors-%DATE%.log'),
      datePattern: 'YYYY-MM-DD',
      zippedArchive: true,
      maxSize: '20m',
      maxFiles: '30d',
      level: 'error',
      format: combine(
        timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
        errorFormat
      )
    }),

    // 成功日志（单独目录）
    new DailyRotateFile({
      filename: path.join(successLogDir, 'success-%DATE%.log'),
      datePattern: 'YYYY-MM-DD',
      zippedArchive: true,
      maxSize: '50m',
      maxFiles: '7d',
      format: combine(
        timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
        successFormat
      )
    }),

    // 开发环境控制台输出
    ...(process.env.NODE_ENV === 'development' ? [
      new transports.Console({
        format: combine(
          format.colorize(),
          printf(info => `${info.timestamp} [${info.level}] ${info.message}`)
        )
      })
    ] : [])
  ]
});

// 请求日志中间件
const requestLogger = (req, res, next) => {
  const start = Date.now();
  res.on('finish', () => {
    const logData = {
      method: req.method,
      path: req.path,
      status: res.statusCode,
      duration: `${Date.now() - start}ms`,
      ip: req.ip
    };

    if (res.statusCode >= 400) {
      logger.error(logData);
    } else {
      logger.info(logData);
    }
  });
  next();
};

module.exports = {
  logger,
  requestLogger,
  logError: (error, context = {}) => {
    logger.error({
      message: error.message,
      stack: error.stack,
      ...context
    });
  }
};